import { Injectable } from '@nestjs/common';
import { CreateLinkDto } from './dto/create-link.dto';
import { UpdateLinkDto } from './dto/update-link.dto';
import { PrismaService } from '../prisma/prisma.service';
import { HttpException, HttpStatus, ConflictException } from '@nestjs/common';
import { ApiResponse } from 'src/common/reponse.interface'; // 引入统一响应格式
@Injectable()
export class LinkService {
  constructor(private prisma: PrismaService) {}

  async create(createLinkDto: CreateLinkDto): Promise<ApiResponse<any>> {
    const { title, href, categoryId, desc } = createLinkDto;
    const existingLink = await this.prisma.link.findFirst({
      where: { href },
    });
    if (existingLink) {
      throw new ConflictException('链接已存在');
    }
    try {
      const result = await this.prisma.link.create({
        data: { title, href, categoryId, desc },
      });
      return {
        statusCode: 200,
        message: '创建成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async findAll(
    page: number = 1,
    pageSize: number = 10,
  ): Promise<ApiResponse<any>> {
    try {
      // 计算跳过数量
      const skip = Number((page - 1) * pageSize);
      // 计算总页数
      const total = await this.prisma.link.count();
      // 计算总页数
      const totalPages = Math.ceil(total / pageSize);
      // 查询数据
      const result = await this.prisma.link.findMany({
        // 跳过数量
        skip,
        // 查询数量
        take: Number(pageSize),
        include: {
          category: true,
          images: {
            include: {
              image: {
                select: {
                  filename: true,
                  filepath: true,
                },
              },
            },
          },
        },
      });
      const data = {
        list: result,
        total,
        totalPages,
      };
      return {
        statusCode: 200,
        message: '查询成功',
        data,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async update(
    id: number,
    updateLinkDto: UpdateLinkDto,
  ): Promise<ApiResponse<any>> {
    const { title, href, categoryId, desc } = updateLinkDto;
    try {
      const result = await this.prisma.link.update({
        where: { id },
        data: { title, href, categoryId, desc },
      });
      return {
        statusCode: 200,
        message: '更新成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async findOne(id: number): Promise<ApiResponse<any>> {
    try {
      const result = await this.prisma.link.findUnique({
        where: { id },
        include: {
          category: true,
          images: {
            include: {
              image: {
                select: {
                  filename: true,
                  filepath: true,
                },
              },
            },
          },
        },
      });
      return {
        statusCode: 200,
        message: '查询成功',
        data: result,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async remove(id: number): Promise<ApiResponse<any>> {
    try {
      await this.prisma.link.delete({ where: { id } });
      return {
        statusCode: 200,
        message: '删除成功',
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  // 搜索 模糊查询
  async search(keyword: string): Promise<ApiResponse<any>> {
    const result = await this.prisma.link.findMany({
      where: { title: { contains: keyword } },
      include: {
        category: true,
      },
    });
    return {
      statusCode: 200,
      message: '查询成功',
      data: result,
    };
  }
}
